package top.kaoshanji.p1ch03a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import top.kaoshanji.u1constant.FileConstant;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/10 16:04
 */
public class ExecuteAround {

    private static final Logger logger = LogManager.getLogger(ExecuteAround.class);

    private static final String FILE = FileConstant.LOCAL_ROOT_PATH.concat("p1ch02a44页a\\data.txt");

    public static void main(String[] args) throws IOException {

        // 代码清单-p1ch03a-44页a：环绕执行模式
        String result = processFileLimited();
        logger.info("...环绕执行模式：{}...", result);


        // 代码清单-p1ch03a-46页a：传递Lambda
        String oneLine = processFile((BufferedReader b) -> b.readLine());
        logger.info("...处理一行：{}...", oneLine);

        String twoLine = processFile((BufferedReader b) -> b.readLine() + b.readLine());
        logger.info("...处理两行：{}...", twoLine);

    }

    public static String processFileLimited() throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(FILE))){
            return br.readLine();
        }
    }

    // 代码清单-p1ch03a-45页b：执行一个行为
    public static String processFile(BufferedReaderProcessor p) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(FILE))){
            return p.process(br);
        }
    }

}
